import { useCallback, useEffect, useState } from 'react'
import { produce } from 'immer'
import useVarList from '../_base/hooks/use-var-list'
import useOutputVarList from '../_base/hooks/use-output-var-list'
import { BlockEnum, VarType } from '../../types'
import type { Var, Variable } from '../../types'
import { useStore } from '../../store'
import type { HtmlExtractorNodeType, OutputVar } from './types'
import useNodeCrud from '@/components/workflow/nodes/_base/hooks/use-node-crud'
import useOneStepRun from '@/components/workflow/nodes/_base/hooks/use-one-step-run'
import { fetchNodeDefault } from '@/services/workflow'
import { useStore as useAppStore } from '@/components/app/store'
import {
  useNodesReadOnly,
} from '@/components/workflow/hooks'

const useConfig = (id: string, payload: HtmlExtractorNodeType) => {
  const { nodesReadOnly: readOnly } = useNodesReadOnly()

  const appId = useAppStore.getState().appDetail?.id

  const defaultConfig = useStore(s => s.nodesDefaultConfigs)[payload.type]
  const { inputs, setInputs } = useNodeCrud<HtmlExtractorNodeType>(id, payload)
  const { handleVarListChange, handleAddVariable } = useVarList<HtmlExtractorNodeType>({
    inputs,
    setInputs,
  })

  const [outputKeyOrders, setOutputKeyOrders] = useState<string[]>([])
  const syncOutputKeyOrders = useCallback((outputs: OutputVar) => {
    setOutputKeyOrders(Object.keys(outputs))
  }, [])
  useEffect(() => {
    if (inputs.url) {
      if (inputs.outputs && Object.keys(inputs.outputs).length > 0)
        syncOutputKeyOrders(inputs.outputs)

      return
    }

    const isReady = defaultConfig && Object.keys(defaultConfig).length > 0
    if (isReady) {
      setInputs({
        ...inputs,
        ...defaultConfig,
      })
      syncOutputKeyOrders(defaultConfig.outputs)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [defaultConfig])

  const handleUrlChange = useCallback((url: string) => {
    const newInputs = produce(inputs, (draft) => {
      draft.url = url
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const handleSelectorChange = useCallback((selector: string) => {
    const newInputs = produce(inputs, (draft) => {
      draft.selector = selector
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const handleAttributeChange = useCallback((attribute: string) => {
    const newInputs = produce(inputs, (draft) => {
      draft.attribute = attribute
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const handleTextChange = useCallback((text: boolean) => {
    const newInputs = produce(inputs, (draft) => {
      draft.text = text
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const {
    handleVarsChange,
    handleAddVariable: handleAddOutputVariable,
    handleRemoveVariable,
    isShowRemoveVarConfirm,
    hideRemoveVarConfirm,
    onRemoveVarConfirm,
  } = useOutputVarList<HtmlExtractorNodeType>({
    id,
    inputs,
    setInputs,
    outputKeyOrders,
    onOutputKeyOrdersChange: setOutputKeyOrders,
  })

  const filterVar = useCallback((varPayload: Var) => {
    return [VarType.string, VarType.number, VarType.secret, VarType.object, VarType.array, VarType.arrayNumber, VarType.arrayString, VarType.arrayObject].includes(varPayload.type)
  }, [])

  // single run
  const {
    isShowSingleRun,
    hideSingleRun,
    toVarInputs,
    runningStatus,
    isCompleted,
    handleRun,
    handleStop,
    runInputData,
    setRunInputData,
    runResult,
  } = useOneStepRun<HtmlExtractorNodeType>({
    id,
    data: inputs,
    defaultRunInputData: {},
  })

  const inputVarValues = (() => {
    const vars: Record<string, any> = {}
    Object.keys(runInputData)
      .forEach((key) => {
        vars[key] = runInputData[key]
      })
    return vars
  })()

  const setInputVarValues = useCallback((newPayload: Record<string, any>) => {
    setRunInputData(newPayload)
  }, [setRunInputData])
  const handleUrlAndSelectorChange = useCallback((url: string, selector: string, outputVariables: OutputVar) => {
    const newInputs = produce(inputs, (draft) => {
      draft.url = url
      draft.selector = selector
      draft.outputs = outputVariables
    })
    setInputs(newInputs)
    syncOutputKeyOrders(outputVariables)
  }, [inputs, setInputs, syncOutputKeyOrders])
  return {
    readOnly,
    inputs,
    outputKeyOrders,
    handleVarListChange,
    handleAddVariable,
    handleRemoveVariable,
    handleUrlChange,
    handleSelectorChange,
    handleAttributeChange,
    handleTextChange,
    handleVarsChange,
    filterVar,
    handleAddOutputVariable,
    isShowRemoveVarConfirm,
    hideRemoveVarConfirm,
    onRemoveVarConfirm,
    // single run
    isShowSingleRun,
    hideSingleRun,
    runningStatus,
    isCompleted,
    handleRun,
    handleStop,
    inputVarValues,
    setInputVarValues,
    runResult,
  }
}

export default useConfig
